package cn.neusoft.service.impl;

import cn.neusoft.bean.Cart;
import cn.neusoft.dao.ICartDao;
import cn.neusoft.dao.impl.CartDao;
import cn.neusoft.query.BaseQuery;
import cn.neusoft.query.CartQuery;
import cn.neusoft.service.ICartService;
import cn.neusoft.vo.PageBean;
import cn.neusoft.vo.ResultBean;

import java.util.List;

public class CartService implements ICartService {
    private ICartDao cartDao;
    public CartService() {
        cartDao = new CartDao();
    }
    @Override
    public ResultBean add(Cart cart) throws Exception {
        if (cart==null||cart.getFoodId()==null) {
            return ResultBean.ERROR("params null");
        }
        int i=cartDao.add(cart);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("add cart fail");
    }
    @Override
    public ResultBean update(Cart cart) throws Exception {
        if (cart==null||cart.getFoodId()==null) {
            return ResultBean.ERROR("params null");
        }
        int i=cartDao.update(cart);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("update cart fail");

    }

    @Override
    public ResultBean delete(Integer id) throws Exception {
        if (id==null) {
            return ResultBean.ERROR("params null");
        }
        int i=cartDao.delete(id);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("delete cart fail");

    }

    @Override
    public ResultBean getById(Integer id) throws Exception {
        if (id==null) {
            return ResultBean.ERROR("params null");
        }
        Cart cart=cartDao.getById(id);
        return cart==null?ResultBean.ERROR("get cart by id fail"):ResultBean.SUCCESS(cart);
    }

    @Override
    public ResultBean getAll() throws Exception {
        List<Cart> carts = cartDao.getAll();
        return ResultBean.SUCCESS(carts);
    }

    @Override
    public ResultBean getByPage(BaseQuery baseQuery) throws Exception {

        if (baseQuery==null) {
            baseQuery=new CartQuery();
        }

        PageBean<Cart> pageBean = new PageBean<>();

        int count = cartDao.getCount(baseQuery);
        pageBean.setTotalRows(count);

        if (count%baseQuery.getPageCount()==0) {
            pageBean.setTotalRows(count/baseQuery.getPageCount());
        }else {
            pageBean.setTotalRows(count/baseQuery.getPageCount()+1);
        }

        List<Cart> cartList = cartDao.getByPage(baseQuery);
        pageBean.setData(cartList);

        return ResultBean.SUCCESS(pageBean);
    }

    @Override
    public ResultBean bathDel(List<Integer> ids) throws Exception {
        if (ids == null || ids.size()==0){
            return ResultBean.ERROR("params null");
        }

        for (Integer id:ids){
            cartDao.delete(id);
        }
        return ResultBean.SUCCESS();
    }
}
